package com.yy.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import com.yy.exception.UnauthorizedException;
import com.yy.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private SecurityProperties securityProperties;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SaInterceptor(handler -> {
                    // 获取所有的URL并进行检查
                    SaRouter.match("/**").check(() -> {
                        // 检查是否登录
                        if (!StpUtil.isLogin()) {
                            // 抛出未登录异常
                            throw new UnauthorizedException("未登录，请先登录！");
                        }
                    });
                }))
                .addPathPatterns("/**")  // 拦截所有路径
                .excludePathPatterns("/user/toLogin")
                .excludePathPatterns(securityProperties.getExcludes());  // 排除指定路径
    }
}